package com.lagou.manager;

import com.lagou.service.UserServiceImpl;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

@Component
public class ZkManager implements InitializingBean, DisposableBean {

    @Autowired
    private ApplicationArguments arguments;

    @Autowired
    private UserServiceImpl userService;

    private CuratorFramework client;

    @Override
    public void afterPropertiesSet() throws Exception {
        // provider 端口
        int port = Integer.parseInt(arguments.getSourceArgs()[0]);
        userService.startServer(port);

        RetryNTimes retryNTimes = new RetryNTimes(0, 1000);
        client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", retryNTimes);
        client.start();

        client.create()
                .creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL)
                .forPath("/providers/" + port);
    }

    @Override
    public void destroy() throws Exception {
        client.close();
    }
}
